﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Web;
using System.Drawing;
using System.Drawing.Imaging;
using CNVP.JShop.UI;
using CNVP.Config;
using CNVP.Framework;


namespace CNVP.JShop.Web.Admin
{
    /// <summary>
    /// Upload 的摘要说明
    /// </summary>
    public class Upload : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            string filename = "", TextOrPicWater = "", SmallWidth = "", MiddleWidth = "", BigWidth = "";
            HttpPostedFile file = context.Request.Files["FileData"];
            string root = context.Server.MapPath(context.Request["folder"]);
            if (file != null)
            {
                try
                {
                    string fileName = file.FileName;
                    filename = getRandomFilename(root) + fileName;
                    file.SaveAs(root + "\\" + filename);

                    SmallWidth = parseFn(filename, "_" + UIPicAddWaterConfig.SmallWidth + "px");
                    ResizeImage(root + "\\" + filename, root + SmallWidth, Convert.ToInt32(UIPicAddWaterConfig.SmallWidth), Convert.ToInt32(UIPicAddWaterConfig.TextSmallFontSize));
                    MiddleWidth = parseFn(filename, "_" + UIPicAddWaterConfig.MiddleWidth + "px");
                    ResizeImage(root + "\\" + filename, root + MiddleWidth, Convert.ToInt32(UIPicAddWaterConfig.MiddleWidth), Convert.ToInt32(UIPicAddWaterConfig.TextMiddleFontSize));
                    BigWidth = parseFn(filename, "_" + UIPicAddWaterConfig.BigWidth + "px");
                    ResizeImage(root + "\\" + filename, root + BigWidth, Convert.ToInt32(UIPicAddWaterConfig.BigWidth), Convert.ToInt32(UIPicAddWaterConfig.TextBigFontSize));

                    //水印
                    TextOrPicWater = parseFn(filename, "_Water");
                    AddWaterPic(root + "\\" + filename, root + "\\" + TextOrPicWater, UIPicAddWaterConfig.IsImageWatermark, UIPicAddWaterConfig.IsTextWatermark);//水印

                    BasePage.DeleteFile(root + "\\" + filename);//原图删除
                    string returnValue = "1|" + SmallWidth + "|" + MiddleWidth + "|" + BigWidth + "|" + TextOrPicWater + "|" + "文件上传成功";
                    context.Response.Write(returnValue); //标志位1标识上传成功，后面的可以返回前台的参数，比如上传后的路径等，中间使用|隔开
                }
                catch
                {
                    context.Response.Write("0|文件上传失败");
                }
            }
            else
            {
                context.Response.Write("0|文件上传失败");
            }
        }

        /// <summary>
        /// 生成一段路径和文件名, 路径跟日期有关, 文件名跟时间有关.
        /// </summary>
        /// <returns>数字字符串,没有后缀</returns>
        static public string getRandomFilename(string root)
        {
            System.Random rand = new System.Random();
            DateTime now = DateTime.Now;
            string path = "";
            path += now.Year.ToString() + "\\";
            path += now.Month.ToString() + "\\";
            path += now.Day.ToString() + "\\";
            if (!Directory.Exists(root + "\\" + path))
            {
                Directory.CreateDirectory(root + "\\" + path);
            }
            path += now.Hour.ToString();
            path += now.Minute.ToString();
            path += now.Second.ToString();
            path += rand.Next(0, 1000);
            return path.Replace("\\", "/");
        }

        /// <summary>
        /// 处理文件名
        /// </summary>
        /// <param name="argFn">路径及文件名</param>
        /// <param name="argSFn">待插入的子串</param>
        /// <returns>操作结果</returns>
        static public string parseFn(string argFn, string argSFn)
        {
            try
            {
                string postfix = argFn.Substring(argFn.LastIndexOf("."));
                return argFn.Substring(0, argFn.LastIndexOf(".")) + argSFn + postfix;
            }
            catch (Exception ex)
            {
                ex.ToString();
            }
            return "";
        }

        /// <summary>
        /// 调整图象尺寸,如果原图片的宽度小于待调整的宽度.则目标图片于原图片一样.不进行调整处理.
        /// </summary>
        /// <param name="srcFile">原图片文件的地址</param>
        /// <param name="objFile">目标文件的地址</param>
        /// <param name="length">目标文件的宽度或高度</param> 
        /// <param name="WaterFonSize">缩列图水印大小</param>
        /// <returns>操作结果.(成功/失败)</returns>
        public static bool ResizeImage(string srcFile, string objFile, int length, int WaterFonSize)
        {
            try
            {
                System.Drawing.Image image = System.Drawing.Image.FromFile(srcFile); //利用Image对象装载源图像  
                //接着创建一个System.Drawing.Bitmap对象，并设置你希望的缩略图的宽度和高度。  
                int srcWidth = image.Width;
                int srcHeight = image.Height;

                int width, height;
                if (srcWidth > length || srcHeight > length)
                {
                    if (srcWidth > srcHeight)
                    {
                        float temp = length * srcHeight / srcWidth;
                        height = (int)temp;
                        height += (temp - height > 0) ? 1 : 0;
                        width = length;
                    }
                    else
                    {
                        float temp = length * srcWidth / srcHeight;
                        width = (int)temp;
                        width += (temp - width > 0) ? 1 : 0;
                        height = length;
                    }
                }
                else
                {
                    width = srcWidth;
                    height = srcHeight;
                }
                Bitmap bmp = new Bitmap(width, height);
                //从Bitmap创建一个System.Drawing.Graphics对象，用来绘制高质量的缩小图。  
                System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(bmp);
                //设置 System.Drawing.Graphics对象的SmoothingMode属性为HighQuality  
                gr.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                //下面这个也设成高质量  
                gr.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                //下面这个设成High  
                gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                //把原始图像绘制成上面所设置宽高的缩小图  
                System.Drawing.Rectangle rectDestination = new System.Drawing.Rectangle(0, 0, width, height);
                gr.DrawImage(image, rectDestination, 0, 0, srcWidth, srcHeight, GraphicsUnit.Pixel);
                //是否在图片上传加文字水印
                if (UIPicAddWaterConfig.IsTextWatermark == "1")//开启文字水印
                {
                    string addText = UIPicAddWaterConfig.TextWatermark;
                    int WaterFonSize_Int = 1;
                    if (WaterFonSize <= 0)
                    {
                        WaterFonSize = WaterFonSize_Int;
                    }
                    System.Drawing.Font f = new System.Drawing.Font(BLL.BLLWaterPic.TextFont(int.Parse(UIPicAddWaterConfig.TextFont)), WaterFonSize);//文字类型，文字大小
                    System.Drawing.Brush b = new System.Drawing.SolidBrush(BLL.BLLWaterPic.TextFontColor(int.Parse(UIPicAddWaterConfig.TextFontColor)));
                    gr.DrawString(addText, f, b, Convert.ToInt32(UIPicAddWaterConfig.TextFloatX), Convert.ToInt32(UIPicAddWaterConfig.TextFloatY));
                }
                //保存图像，大功告成！
                ImageFormat imageFormat = image.RawFormat;
                bmp.Save(objFile, imageFormat);
                //最后别忘了释放资源（译者PS：C#可以自动回收吧）  
                gr.Dispose();
                bmp.Dispose();
                image.Dispose();
                return true;
            }
            catch (Exception ex)
            {
                ex.ToString();
                return false;
            }
        }

        /// <summary>
        /// 在图片上生成图片水印
        /// </summary>
        /// <param name="Path">原服务器图片路径</param>
        /// <param name="Path_syp">生成的带图片水印的图片路径</param>
        /// <param name="IsImageWatermark">图片水印是否开启</param>
        /// <param name="IsTextWatermark">文字水印是否开启</param>
        protected void AddWaterPic(string Path, string Path_syp, string IsImageWatermark, string IsTextWatermark)
        {
            System.Drawing.Image image = System.Drawing.Image.FromFile(Path);
            //System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(image);
            System.Drawing.Bitmap bit = new System.Drawing.Bitmap(image.Width, image.Height);
            Graphics gr = Graphics.FromImage(bit);
            if (IsTextWatermark == "1")//开启文字水印
            {
                string addText = UIPicAddWaterConfig.TextWatermark;
                int TextOriginalFontSize_Int = 1;
                if (Convert.ToInt32(UIPicAddWaterConfig.TextOriginalFontSize) <= 0)
                {
                    TextOriginalFontSize_Int = 1;
                }
                else
                {
                    TextOriginalFontSize_Int = Convert.ToInt32(UIPicAddWaterConfig.TextOriginalFontSize);
                }
                System.Drawing.Font f = new System.Drawing.Font(BLL.BLLWaterPic.TextFont(int.Parse(UIPicAddWaterConfig.TextFont)), TextOriginalFontSize_Int);//文字类型，文字大小
                System.Drawing.Brush b = new System.Drawing.SolidBrush(BLL.BLLWaterPic.TextFontColor(int.Parse(UIPicAddWaterConfig.TextFontColor)));
                gr.DrawString(addText, f, b, Convert.ToInt32(UIPicAddWaterConfig.TextFloatX), Convert.ToInt32(UIPicAddWaterConfig.TextFloatY));
            }
             //是否在图片上传加图片水印
            if (IsImageWatermark == "1")//开启图片水印
            {
                try
                {
                    if (UIPicAddWaterConfig.ImageWatermark != "")
                    {
                        string Path_WaterPic = HttpContext.Current.Server.MapPath("../UploadFile/Logo/" + UIPicAddWaterConfig.ImageWatermark);
                        System.Drawing.Image copyImage = System.Drawing.Image.FromFile(Path_WaterPic);
                        gr.DrawImage(copyImage, new System.Drawing.Rectangle(int.Parse(UIPicAddWaterConfig.ImageFloatX), int.Parse(UIPicAddWaterConfig.ImageFloatY), copyImage.Width, copyImage.Height), new Rectangle(0, 0, copyImage.Width, copyImage.Height), System.Drawing.GraphicsUnit.Pixel);
                    }
                }
                catch { }
            }
            gr.Dispose();
            image.Save(Path_syp);
            image.Dispose();
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}